<?php

session_start();
// ini_set('session.cookie_domain','local.crosapi.com'); //无影响

$action = $_REQUEST['action'];

$ref = isset($_SERVER['HTTP_REFERER'])?trim($_SERVER['HTTP_REFERER'],"/"):"*";
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Origin:'.$ref);
// header('Access-Control-Allow-Methods: GET, POST');
// header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

$data=['action'=>$action];
switch ($action) {
	case 'login':
		$login_time = "user is login @ ".date('Y-m-d H:i:s');
		$_SESSION['login_time'] = $login_time;
		$md5 = md5($login_time);
		$data['token']= $md5;
		file_put_contents(__DIR__."/token/{$md5}.txt", $login_time);
		break;
	
	case 'logout':
		$data['login_time']= 'no login';
		$token = isset($_REQUEST['token'])?$_REQUEST['token']:"";
		if($token){
			$file = __DIR__."/token/{$token}.txt";
			if(file_exists($file)) {
				$data['login_time']= file_get_contents($file);
				unlink($file);
			}
		}else{
			if(isset($_SESSION['login_time'])){
				$data['login_time']= $_SESSION['login_time'];
			}
		}
		session_destroy();
		break;
	case 'info':
		$token = isset($_REQUEST['token'])?$_REQUEST['token']:"";
		$data['login_time']= 'no login';
		if($token){
			$file = __DIR__."/token/{$token}.txt";
			if(file_exists($file)) {
				$data['login_time']= file_get_contents($file);
			}
		}else{
			if(isset($_SESSION['login_time'])){
				$data['login_time']= $_SESSION['login_time'];
			}
		}
		break;
	case 'api':
		$data['msg']='this api not need login info ';
		break;
	default:
		# code...
		break;
}

//支持jsonp的callback
$callback = isset($_REQUEST['callback'])?$_REQUEST['callback']:"";
if($callback){
	echo "{$callback}(".json_encode($data).")";
}else{
	echo json_encode($data);
}